package com.sky.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.StatusConstant;
import com.sky.entity.Category;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user/dish")
@RestController("userDishController")
@Api(tags = "C端-菜品相关接口")
@RequiredArgsConstructor
@Slf4j
public class DishController {

    private final DishService dishService;

    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 根据分类id获取菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id获取菜品")
    public Result<List<DishVO>> list(Long categoryId) {
        log.info("获取分类id为{}的菜品",categoryId);
        //构造key ，规则sky:dish:categoryId
        String key="sky:dish:"+categoryId;
        long ttl=30L;
        //查询redis中是否存在菜品数据
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        //如果存在，直接返回
        if(jsonStr != null && !jsonStr.isEmpty()){
            List<DishVO> dishVOList = JSON.parseArray(jsonStr, DishVO.class);
            log.info("通过redis命中{}",dishVOList);
            return Result.success(dishVOList);
        }
        //如果不存在，查询数据库，并将查到的数据保存到redis
        Category category = Category.builder()
                .id(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<DishVO> byCategoryId =
                dishService.getByCategoryId(category);
        //将查到的数据存入redis
        String jsonString = JSON.toJSONString(byCategoryId);
        stringRedisTemplate.opsForValue().set(key, jsonString,ttl, TimeUnit.MINUTES);
        return Result.success(byCategoryId);
    }
}
